#include "TcpServer.hpp"
#include "Protocal.hpp"
#include "Daemon.hpp"
#include <memory>
#include <signal.h>

void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " port\n" << std::endl;
}

Respense calculatorHelper(const Request& req)
{
    Respense resp(0, 0, req._x, req._y, req._op);
    switch(req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0) resp._code = 1;
        else resp._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0) resp._code = 2;
        else resp._result = req._x / req._y;
        break;
    default:
        resp._code = 3;
        break;
    }

    return resp;
}

void calcutator(int sock)
{
    std::string inbuffer;
    while (true)
    {
        // 1. 读取数据
        bool res = Recv(sock, &inbuffer); 
        if (!res) break;  // 没有读到就是出错了
        // 2.协议解析 -> 保证读到的是一个完整的报文
        std::string package = DeCode(inbuffer);
        if (package.empty())    continue;
        logMessage(NORMAL, "%s", package.c_str());

        // 3.反序列化  字节流 -> 结构化
        Request req;
        req.Deserialized(package);
        // 4.业务逻辑
        Respense resp = calculatorHelper(req);
        // 6.序列化
        std::string respString = resp.Serialize();
        respString = EnCode(respString);
        Send(sock, respString);
    }
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[1]);
        exit(0);
    }

    // 进程守护
    MyDaemon();

    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindServer(calcutator);
    server->start();
    return 0;
}
